package org.frasermccrossan.toneitdown;

import java.text.DateFormat;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

class Notify {
	
	private static final int NOTIFICATION_ID = 1;

	// apply all profile settings described by the database, including
	// alarms and notifications
	static void applyProfile(Context context) {
		ProfileDatabaseHelper dbh = new ProfileDatabaseHelper(context);
		ProfileInfo info = dbh.getProfileInfo();
		if (info != null) {
			Profile currentProfile = dbh.getProfileById(info.currentProfile);
			if (currentProfile == null) {
				dbh.close();
				return;
			}
			Profile timedProfile = dbh.getProfileById(info.timedProfile);
			Profile activeProfile;
			int icon;
			String tickerText;
			String contentText;
			if (info.isTimed()) {
				activeProfile = timedProfile;
				icon = R.drawable.ic_stat_timed;
				DateFormat dateFormat = android.text.format.DateFormat.getTimeFormat(context);
				tickerText = String.format("%s (%s)", timedProfile.name, currentProfile.name);
				contentText = String.format(context.getString(R.string.profile_will_revert), currentProfile.name,
						dateFormat.format(info.timedExpiry));
			}
			else {
				activeProfile = currentProfile;
				icon = R.drawable.ic_stat_current;
				tickerText = currentProfile.name;
				contentText = "";
			}
			String contentTitle = String.format(context.getString(R.string.profile_is), activeProfile.name);
			Notification.Builder nb = new Notification.Builder(context);
			nb.setSmallIcon(icon);
			nb.setTicker(tickerText);
			nb.setOngoing(true);
			nb.setContentTitle(contentTitle);
			nb.setContentText(contentText);
			nb.setOnlyAlertOnce(false);
			nb.setWhen(System.currentTimeMillis());
			Intent notificationIntent = new Intent(context, PickProfile.class);
			PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent,
					PendingIntent.FLAG_CANCEL_CURRENT);
			nb.setContentIntent(contentIntent);
			NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
			notificationManager.notify(NOTIFICATION_ID, nb.getNotification());
			activeProfile.apply(context, false);
			if (info.isTimed()) {
				Intent intent = new Intent(context, ProfileExpirer.class);
				PendingIntent sender = PendingIntent.getBroadcast(context, 12345, intent,
						PendingIntent.FLAG_CANCEL_CURRENT);
				AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
				am.set(AlarmManager.RTC_WAKEUP, info.timedExpiry, sender);
			}
			dbh.close();
		}
	}
}
